import messageManage
import re, time, requests, json
from webService.global_token import _global_access_token,global_update_access
from LoggerBase import log


def get_token():
    log.warning("开始重新获取token")
    payload_access_token = {
        'grant_type': 'client_credential',
        'appid': 'wxd9cfdc38b3bf4c23',
        'secret': 'fcae013247960e926065a8d6a3e98f88'
    }
    token_url = 'https://api.weixin.qq.com/cgi-bin/token'
    r = requests.get(token_url, params=payload_access_token)
    dict_result = (r.json())
    # print(dict_result)
    global_update_access(dict_result['access_token'])
    return dict_result['access_token']


def get_openid(self):
    """
    获取所有粉丝的openid
    """
    next_openid = ''
    url_openid = 'https://api.weixin.qq.com/cgi-bin/user/get?access_token=%s&next_openid=%s' % (
        self.access_token, next_openid)
    ans = requests.get(url_openid)
    print(ans.content)
    open_ids = json.loads(ans.content)['data']['openid']
    return open_ids


def sendmsg(msg, wx_id):
    """
    给所有粉丝发送文本消息
    """
    if "token" not in _global_access_token:
        get_token()
    access_token = _global_access_token["token"]
    url = "https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token={}".format(access_token)
    body = {
        "touser": wx_id,
        "msgtype": "text",
        "text":
            {
                "content": msg
            }
    }
    data = bytes(json.dumps(body, ensure_ascii=False).encode('utf-8'))
    # print(data)
    response = requests.post(url, data=data)
    # 这里可根据回执code进行判定是否发送成功(也可以根据code根据错误信息)
    result = json.loads(response.text)
    # print(result)
    return result


def send_msg_active(msg, wx_id):
    result = sendmsg(msg, wx_id)
    if "errcode" in result:
        if result["errcode"] in [40014, 41001, 42001]:
            get_token()
            sendmsg(msg, wx_id)

